package utl.mofen.dbHandler;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import utl.mofen.utils.FileUtil;
import utl.mofen.utils.StringUtil;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class DBHandlerFactory {
	private static final Logger logger = Logger.getLogger(DBHandlerFactory.class);
	private static ApplicationContext ctx = null;
	
	public static void checkInitialize(String file)
	{
		if (StringUtil.stringIsEmpty(file))
		{			
			file = FileUtil.getRootPath() + "DBHandler.xml";			
		}
		if (ctx==null)
		{
			System.out.println("载入DBHandlerFactory配置文件:" + file);
			ctx = new FileSystemXmlApplicationContext(file);
		}
	}
	
	public static IDBHandler createHandler(String pluginName) throws Exception
	{		
		if (ctx==null)
		{
			throw new Exception("先调用checkInitialize进行初始化");
		}
		
		if (StringUtil.stringIsEmpty(pluginName))
		{
			throw new Exception("没有配置知道要执行的插件名称");			
		}
	
		return (IDBHandler)ctx.getBean(pluginName);
	}
	
	public static IDBHandler createHandler(JsonObject config) throws Exception
	{		
		JsonElement e = config.get("plugin");
		if (e==null)
		{
			throw new Exception("没有配置plugin");
		}
		
		if (e.getAsJsonObject().get("name")==null)
		{
			throw new Exception("没有配置知道要执行的插件名称(plugin.name)");			
		}
		
		String pluginName = e.getAsJsonObject().get("name").getAsString();	
		logger.info("创建了插件" + pluginName);
		return createHandler(pluginName);
	}
}
